package com.hjqjl.module_home;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;

public class BitmapUtils {
    /**
     * 正片叠底帮助类
     *
     * @param cartoonImage 底图（要与背景图混合的图）
     * @param bgImage      背景图
     * @return 正片叠底处理好的bitmap
     */
    public static Bitmap setModeMultiply(Bitmap cartoonImage, Bitmap bgImage) {
        int cha = bgImage.getHeight() - cartoonImage.getHeight();
        LogUtils.v("bgImageHeight:" + bgImage.getHeight() + "---cartoonImageHeight:" + cartoonImage.getHeight());
        if (cha < 0) {
            ToastUtils.showShort("遮罩图高度小于背景图,返回了背景图");
            return bgImage;
        }
        Bitmap resultBitmap = Bitmap.createBitmap(bgImage.getWidth(), bgImage.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(resultBitmap);
        Paint mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setFilterBitmap(true);
        canvas.drawBitmap(cartoonImage, 0, 0, mPaint);

        //新添加的代码，把这遮罩图绘制到白色的图片上
        final Bitmap resultBitmap2 = Bitmap.createBitmap(bgImage.getWidth(), bgImage.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas2 = new Canvas(resultBitmap2);
        canvas2.drawColor(Color.WHITE);
        canvas2.drawBitmap(resultBitmap, 0, cha, mPaint);

        //4.设置画笔的正片叠底的效果
        mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.MULTIPLY));
        //5.最后画背景图片，实现效果
        canvas2.drawBitmap(bgImage, 0, 0, mPaint);
        //6.清除画笔效果
        mPaint.setXfermode(null);

        return resultBitmap2;
    }

    /**
     * 缩放bitmap
     */
    public static Bitmap imageScale(Bitmap bitmap, int dst_w, int dst_h) {
        int src_w = bitmap.getWidth();
        int src_h = bitmap.getHeight();
        float scale_w = ((float) dst_w) / src_w;
        float scale_h = ((float) dst_h) / src_h;
        Matrix matrix = new Matrix();
        matrix.postScale(scale_w, scale_h);
        Bitmap dstbmp = Bitmap.createBitmap(bitmap, 0, 0, src_w, src_h, matrix,
                true);
        return dstbmp;
    }
}
